import store from '@/store';
import {
	useI18n
} from "@/locales/setupI18n";
import {
	checkStatus
} from "@/utils/bluetooth/checkStatus";

import tsplClient from '@/utils/printer/gprinter/tspl';

/** 创建打印命令 */
export function createPrintCommand() {
	const paperSize = store.getters.getPrinterPaperSize;
	const paperGap = store.getters.getPrinterPaperGap;
	const paperBline = store.getters.getPrinterPaperBline;

	let command;
	// TODO：打印指令集判断逻辑
	command = tsplClient.createNew();
	command.size(paperSize.Width, paperSize.Height); // 设定卷标纸的宽度和长度
	command.gap(paperGap.M, paperGap.N); // 定义两张卷标纸间的垂直间距距离
	if (paperBline && (paperBline.M > 0 || paperBline.N > 0)) {
		command.bline(paperBline.M, paperBline.N); // 定义两张卷标纸间的垂直间距距离
	}
	command.cls(); // 清除图像缓冲区(image buffer)的数据

	return command;
}

/** 打印图片
 * @param command 打印命令
 * @param mask 是否启用遮罩
 * @param errorMessageMode 错误消息提示模式: 'none' | 'modal' | 'message'
 */
export function printImage(command, mask = true, errorMessageMode = 'message') {

}



/** 准备发送，根据每次发送字节数来处理分包数量
 * @param buff 发送字节
 */
export function prepareSend(buff) {
	//console.log(buff)
	var time = that.data.oneTimeData
	var looptime = parseInt(buff.length / time);
	var lastData = parseInt(buff.length % time);
	//console.log(looptime + "---" + lastData)
	that.setData({
		looptime: looptime + 1,
		lastData: lastData,
		currentTime: 1,
	})
	send(buff);
}

/** 分包发送
 * @param command 打印命令
 * @param mask 是否启用遮罩
 * @param errorMessageMode 错误消息提示模式: 'none' | 'modal' | 'message'
 */
export function send(command, mask = true, errorMessageMode = 'message') {
	var that = this
	var currentTime = that.data.currentTime
	var loopTime = that.data.looptime
	var lastData = that.data.lastData
	var onTimeData = that.data.oneTimeData
	var printNum = that.data.printerNum
	var currentPrint = that.data.currentPrint
	var buf
	var dataView
	if (currentTime < loopTime) {
		buf = new ArrayBuffer(onTimeData)
		dataView = new DataView(buf)
		for (var i = 0; i < onTimeData; ++i) {
			dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
		}
	} else {
		buf = new ArrayBuffer(lastData)
		dataView = new DataView(buf)
		for (var i = 0; i < lastData; ++i) {
			dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
		}
	}
	//console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
	uni.writeBLECharacteristicValue({
		deviceId: app.BLEInformation.deviceId,
		serviceId: app.BLEInformation.writeServiceId,
		characteristicId: app.BLEInformation.writeCharaterId,
		value: buf,
		success: function(res) {
			if (currentTime <= loopTime) {
				// wx.showLoading({
				//   title: '传输中...',
				// })
			} else {
				wx.showToast({
					title: '已打印第' + currentPrint + '张成功',
				})
			}
			//console.log(res)
		},
		fail: function(e) {
			wx.showToast({
				title: '打印第' + currentPrint + '张失败',
				icon: 'none',
			})
			//console.log(e)
		},
		complete: function() {
			currentTime++
			if (currentTime <= loopTime) {
				that.setData({
					currentTime: currentTime
				})
				that.Send(buff)
			} else {
				if (currentPrint == printNum) {
					that.setData({
						looptime: 0,
						lastData: 0,
						currentTime: 1,
						isReceiptSend: false,
						currentPrint: 1
					})
				} else {
					currentPrint++
					that.setData({
						currentPrint: currentPrint,
						currentTime: 1,
					})
					that.Send(buff)
				}
			}
		}
	})
}

/** 发送打印命令
 * @param command 打印命令
 * @param mask 是否启用遮罩
 * @param errorMessageMode 错误消息提示模式: 'none' | 'modal' | 'message'
 */
export function sendPrintCommand(command, mask = true, errorMessageMode = 'message') {
	if (!command) {
		return;
	}
	const printerInfo = store.getters.getPrinterInfo;
	const {
		t
	} = useI18n();

	command.print();

	let buff = command.getCommand();
	let uintBuff = Array.from(buff);

	function splitArray(datas, size) {
		let result = {};
		let j = 0;
		for (let i = 0; i < datas.length; i += size) {
			result[j] = datas.slice(i, i + size);
			j++;
		}
		// console.log(result);
		return result;
	}
	let sendloop = splitArray(uintBuff, 20);
	// console.log(sendloop.length);
	function realWriteData(sendloop, i) {
		let data = sendloop[i]
		if (typeof(data) == "undefined") {
			return
		}
		// console.log("第【" + i + "】次写数据" + data);
		let buffer = new ArrayBuffer(data.length);
		let dataView = new DataView(buffer);
		for (let j = 0; j < data.length; j++) {
			dataView.setUint8(j, data[j]);
		}
		uni.writeBLECharacteristicValue({
			deviceId: printerInfo.deviceId,
			serviceId: printerInfo.writeServiceId,
			characteristicId: printerInfo.writeCharaterId,
			value: buffer,
			success(res) {
				realWriteData(sendloop, i + 1);
			},
			fail(e) {
				// uni.showModal({
				// 	title: '向蓝牙写入数据失败',
				// 	content: JSON.stringify(e)
				// });
				// console.log('writeBLECharacteristicValue_fail', e);
				checkStatus(e.errCode, e.errMsg, errorMessageMode);
			}
		})
	}
	let i = 0;
	// 发送打印
	try {
		if (mask) {
			uni.showLoading({
				title: t('common.loadingText'),
				mask: true
			});
		}

		// uni.showModal({
		// 	title: '发送打印',
		// 	content: JSON.stringify({
		// 	deviceId: printerInfo.deviceId,
		// 	serviceId: printerInfo.writeServiceId,
		// 	characteristicId: printerInfo.writeCharaterId})
		// });

		realWriteData(sendloop, i);

		if (mask) {
			uni.hideLoading();
		}
	} catch (err) {} finally {
		if (mask) {
			uni.hideLoading();
		}
	}

}
